package com.apestech.framework.run.core;

import com.apestech.framework.run.callback.ThreadCallBackHandler;
import com.apestech.framework.util.UnitUtil;

public class SingleRun {
	private String name;
	private boolean bcostTime=false;
	private boolean bcostJVM=false;
	private boolean bclearJVM=false;
	private long startTime;
	private long endTime;
	private int startMemory;
	private int endMemory;
	private long costTime=-1;
	private int costMemory=-1;
	private int costGcMemory=-1;
	
	public SingleRun(){
	}
	
	public SingleRun(String name){
		this.name=name;
	}
	
	public SingleRun(String name, boolean system){
		this.name=name;
		setSystem(system);
	}
	
	public void setSystem(boolean system){
		if(system){
			this.bcostJVM=true;
			this.bcostTime=true;
		} else {
			this.bcostTime=false;
		}
	}
	
	public void setName(String name){
		this.name=name;
	}
	
	public void setBcostTime(boolean bcostTime){
		this.bcostTime=bcostTime;
	}
	
	public void setBcostJVM(boolean bcostJVM){
		this.bcostJVM=bcostJVM;
	}
	
	public void setBclearJVM(boolean bclearJVM){
		this.bclearJVM=bclearJVM;
	}
	
	public long getCostTime(){
		return this.costTime;
	}
	
	public int getCostMemory(){
		return this.costMemory;
	}
	
	public int getCostGcMemory(){
		return this.costGcMemory;
	}
	
	public String getName(){
		return this.name;
	}
	
	public void run(ThreadCallBackHandler callBackHandler) {
		if(this.bcostTime){
			this.startTime = System.currentTimeMillis();
		}
		if(this.bcostJVM){
			this.startMemory = (int)Runtime.getRuntime().totalMemory();
		}
		
		try {
			callBackHandler.run();
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}  //this.name
		
		if(this.bcostTime){
			this.endTime = System.currentTimeMillis();
			this.costTime=endTime - startTime;
			System.out.println("程序运行时间：" + UnitUtil.getMinutes(this.costTime));
		}
		if(this.bcostJVM){
			try {
				this.endMemory = (int)Runtime.getRuntime().totalMemory();
				this.costMemory=endMemory-startMemory;
				System.out.println("程序使用内存："+UnitUtil.getSize(this.costMemory));
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		if(this.bclearJVM){
			System.gc();
			int endMemory1 = (int)Runtime.getRuntime().totalMemory();
			try {
				this.costGcMemory=endMemory1-endMemory;
				System.out.println("执行释放内存操作之后，程序使用内存："+UnitUtil.getSize(this.costGcMemory));
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
	}
	
}
